<?php

class Controller {

    private $load;
    private $model;
    private $config;

    public function __construct($config)
    {
        $this->config = $config;
        $this->load = new Load();
        $this->model = new Model($config);
        $p = null;
        if (isset($_GET['p']))
        {
            $p = htmlentities($_GET['p'], ENT_QUOTES, "UTF-8");
        }
        if (!isset($_SESSION['connect']) or $_SESSION['connect'] != true)
        {
            $p = 'login';
        }
        switch ($p)
        {
            case null:
                $this->home();
                break;
            case "edit":
                $this->edit();
                break;
            case "delete":
                $this->delete();
                break;
            case "login":
                $this->login();
                break;
            case "logout":
                $this->logout();
                break;
            default:
                $this->login();
                break;
        }
    }

    private function home()
    {
        $pages = $this->model->get_pages();
        $data['mode'] = $this->get_mode();
        $block_count = $this->model->block_count($data['mode']);
        $blocks_per_page = $data['mode']['limit'];
        $page_count = ceil($block_count / $blocks_per_page);
        $page = 0;
        if (isset($_GET['page']) and $_GET['page'] != null)
        {
            $page = intval($_GET['page']) - 1;
            if ($page == -1)
            {
                $page = 0;
            }
        }
        $data['block_count'] = $block_count;
        $data['pages'] = $pages;
        $data['page_count'] = $page_count;
        $data['page'] = $page;
        $data['blocks'] = $this->model->get_blocks($page, $blocks_per_page, $data['mode']);
        $this->load->view('home.php', $data);
    }

    private function get_mode()
    {
        $mode = array(
            'order' => 'alpha',
            'page' => 'default',
            'limit' => 2,
            'search' => ''
        );
        if (isset($_POST['confirm']))
        {
            $mode['order'] = $_POST['order'];
            $mode['page'] = $_POST['page'];
            $mode['limit'] = $_POST['limit'];
            $mode['search'] = trim($_POST['search']);
            $_SESSION['mode'] = $mode;
        }
        else if (isset($_SESSION['mode']))
        {
            $mode = $_SESSION['mode'];
        }
        return $mode;
    }

    private function get_id()
    {
        $id = false;
        if (isset($_GET['id']) and $_GET['id'] != 0 and is_int(intval($_GET['id'])))
        {
            $id = intval($_GET['id']);
        }
        else
        {
            header('Location: index.php');
            exit;
        }
        return $id;
    }

    private function edit()
    {
        $id = $this->get_id();
        $refresh_content = true;
        $message = array(
            'text' => '',
            'type' => 'highlight'
        );
        if (isset($_POST['back']))
        {
            $content = $_POST['content'];
            $data['block'] = $this->model->get_current_block($id);
            $content_temp = $data['block']['content_block'];
            if ($content != $content_temp)
            {
                $message['text'] = 'Le bloc a été modifié mais n\'a pas été enregistré. 
                    <strong><a style="color: #FFF;" href="index.php">Quitter sans enregistrer.</a></strong>';
                $message['type'] = 'error';
                $refresh_content = false;
            }
            else
            {
                header('Location: index.php');
                exit;
            }
        }
        if ($id != false)
        {
            if (isset($_POST['content']) and isset($_POST['save']))
            {
                $content = $_POST['content'];
                $data['block'] = $this->model->get_current_block($id);
                $content_temp = $data['block']['content_block'];
                if ($content == $content_temp)
                {
                    $message['text'] = "Le bloc n'a pas été modifié.";
                    $message['type'] = 'highlight';
                }
                else
                {
                    $edit_ok = $this->model->edit_block($id, $content);
                    if ($edit_ok)
                    {
                        $message['text'] = "Le bloc a bien été modifié.";
                        $message['type'] = 'success';
                    }
                    else
                    {
                        $message['text'] = "Erreur lors de la modification du bloc.";
                        $message['type'] = 'error';
                    }
                }
            }
            $data['message'] = $message;
            $data['block'] = $this->model->get_current_block($id);
            if (!$refresh_content)
            {
                $data['block']['content_block'] = $content;
            }
            $data['block']['content_block'] = htmlentities($data['block']['content_block'], ENT_QUOTES, "UTF-8");
            $this->load->view('edit.php', $data);
        }
    }

    private function delete()
    {
        $id = $this->get_id();
        $message = array(
            'text' => '',
            'type' => 'highlight'
        );
        if ($id != false)
        {
            $code_ok = false;
            $delete_ok = false;
            if (isset($_POST['pass']) and $_POST['pass'] != null)
            {
                $pass = $_POST['pass'];
                $code_ok = $this->model->check_pass($pass);
                if ($code_ok)
                {
                    $delete_ok = $this->model->delete_block($id);
                    if ($delete_ok)
                    {
                        $message['text'] = 'Le bloc a bien été supprimé, vous allez être redirigé vers l\'accueil.';
                        $message['type'] = 'success';
                        $data['redirect'] = true;
                    }
                    else
                    {
                        $message['text'] = 'Erreur lors de la suppression du bloc.';
                        $message['type'] = 'error';
                    }
                }
                else
                {
                    $message['text'] = 'Vous avez saisi un mauvais mot de passe.';
                    $message['type'] = 'error';
                }
            }
            $data['message'] = $message;
            $data['block'] = $this->model->get_current_block($id);
            $data['code_ok'] = $code_ok;
            $data['delete_ok'] = $delete_ok;
            $this->load->view('delete.php', $data);
        }
    }

    private function login()
    {
        $message = array(
            'text' => '',
            'type' => 'highlight'
        );
        if (!isset($_COOKIE['spam']) or (isset($_COOKIE['spam']) and $_COOKIE['spam'] == null))
        {
            if (isset($_POST['pass']) and $_POST['pass'] != '')
            {
                $input_pass = htmlentities($_POST['pass'], ENT_QUOTES, "UTF-8");
                $pass_ok = $this->model->check_pass($input_pass);
                if ($pass_ok == true)
                {
                    $_SESSION['connect'] = true;
                    $_SESSION['spam'] = 0;
                    $message['text'] = 'Vous êtes maintenant connecté(e), vous allez être redirigé(e) vers l\'accueil.';
                    $message['type'] = 'success';
                    $data['redirect'] = 1;
                }
                else
                {
                    $message['text'] = 'Vous avez saisi un mauvais mot de passe.';
                    $message['type'] = 'error';
                }
                if (isset($_SESSION['spam']))
                {

                    if ((!isset($_COOKIE['spam']) or $_COOKIE['spam'] == null) and $_SESSION['spam'] >= 9)
                    {
                        $_SESSION['spam'] = 0;
                        setcookie('spam', true, time() + 60);
                        $message['text'] = 'Vous avez tapez un mot de passe incorrect à 10 reprises. <strong>Veuillez patientez 10 minutes.</strong>';
                        $message['type'] = 'error';
                    }
                    else
                    {
                        $_SESSION['spam']++;
                    }
                }
                else
                {
                    $_SESSION['spam'] = 0;
                }
            }
        }
        else
        {
            $message['text'] = 'Vous avez tapez un mot de passe incorrect à 10 reprises. <strong>Veuillez patientez 10 minutes.</strong>';
            $message['type'] = 'error';
        }
        $data['message'] = $message;
        $this->load->view("login.php", $data);
    }

    private function logout()
    {
        session_destroy();
        $data['message']['text'] = 'Vous êtes maintenant déconnecté(e).';
        $data['message']['type'] = 'success';
        $this->load->view("login.php", $data);
    }

}
